package applet.login;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import sql.SQLInterface;

import data.CMSRes;
import data.account.Account;

import applet.login.components.LoginBackground;
import applet.login.components.LoginPane;
import applet.view.BaseCMSView;

public class CMSLoginView extends BaseCMSView
{
	private LoginPane loginPane;
	
	public CMSLoginView()
	{
		JPanel view = new LoginBackground(new GridBagLayout());
		view.add(loginPane = new LoginPane(this), new GridBagConstraints());
		setView(view);
	}
	
	public boolean attemptLogin(String username, String password)
	{
		Account account = SQLInterface.attemptLogin(username, password);
		if(account != null)
		{
			viewController().deferToView(account.createView());
			return true;
		}
		else
		{
			JOptionPane.showMessageDialog(CMSRes.frame(), 
					"No account with the specified name and password exists. Please try again.",
					"Login Failed",
					JOptionPane.ERROR_MESSAGE);
		}
		return false;
	}
	
	public boolean attemptRegister(String username, String password)
	{
		Account account = SQLInterface.attemptRegister(username, password);
		if(account != null)
		{
			viewController().deferToView(account.createView());
			return true;
		}
		else
		{
			JOptionPane.showMessageDialog(CMSRes.frame(), 
					"An account with the same username already exists! Please try again.",
					"Registration Failed",
					JOptionPane.ERROR_MESSAGE);
		}
		return false;
	}
	
	public void makeActive() { loginPane.reset(); }
	public void makeInactive() { loginPane.reset(); }
}